import 'package:flutter_model_package/CourseClass.dart';
import 'package:flutter_model_package/CourseEnrollment.dart';
import 'package:flutter_model_package/CourseLesson.dart';
import 'package:flutter_model_package/Employee.dart';
import 'package:flutter_model_package/parse_base.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';

import 'scholar.dart';

class CourseAttendance extends MSParseBase {
  CourseAttendance() : super("CourseAttendance");

  CourseAttendance.cloe() : this();

  @override
  CourseAttendance clone(Map<String, dynamic> map) =>
      CourseAttendance.cloe()..fromJson(map);

  static Future<List<Map>> forEnrollemt(
      CourseClass courseClass, Employee employee, CourseLesson lesson) async {
    var enrollments = await CourseEnrollment.forTeaClass(courseClass, employee);

    return Future.wait(enrollments.map((enroll) async {
      var query = QueryBuilder(CourseAttendance())
        ..whereEqualTo("class", courseClass)
        ..whereEqualTo("scholar", enroll["student"])
        ..whereEqualTo("lesson", lesson);
      var rep = await query.query();
      if (rep.results != null && rep.success) {
        return {"scholar": enroll["student"], "attend": rep.results.first};
      } else {
        return {"scholar": enroll["student"], "attend": "undefined"};
      }
    }).toList());
  }

  static Future<ParseResponse> updateAttendance(
      dynamic stuAttend, CourseLesson lesson, String status) async {
    CourseAttendance attendance = new CourseAttendance();
    if (stuAttend["attend"] != "undefined") {
      attendance.set("objectId", stuAttend["attend"]["objectId"]);
    }
    attendance.set("scholar", stuAttend["scholar"]);
    attendance.set("class", lesson["class"]);
    attendance.set("lesson", lesson);
    attendance.set("status", status);
    return await attendance.save();
  }

  static QueryBuilder<CourseAttendance> forScholarAttendance(
      Scholar scholar, CourseLesson lesson, CourseClass courseClass) {
    return QueryBuilder(CourseAttendance())
      ..whereEqualTo("class", courseClass)
      ..whereEqualTo("lesson", lesson)
      ..whereEqualTo("scholar", scholar)
      ..includeObject(["scholar","lesson","class"]);
  }
}
